package com.nacos.novelzoolserver.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>跨域过滤器</p>
 *
 * @author zy 刘会发
 * @since 2020/4/2
 */
@Component
@RefreshScope
public class ProxyFilter extends ZuulFilter {

    @Value("${zuul.shouldFilter}")
    private boolean shouldFilter;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return shouldFilter;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();

        //解决跨域问题
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
        response.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        response.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");


        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            currentContext.setSendZuulResponse(false); //验证请求不进行路由
            currentContext.setResponseStatusCode(HttpStatus.OK.value());//返回验证成功的状态码
            currentContext.set("isSuccess", true);
            return null;
        }
        currentContext.setSendZuulResponse(true); //对请求进行路由
        currentContext.setResponseStatusCode(HttpStatus.OK.value());
        currentContext.set("isSuccess", true);
        return null;
    }
}
